package com.prb.server.netty;


import com.prb.netty.code.SmartCarDecoder;
import com.prb.netty.code.SmartCarEncoder;
import com.prb.server.netty.handler.SimpleHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RpcServer {


    private String ip = "127.0.0.1";

    private Integer port = 8088;


    public RpcServer() {
    }

    public RpcServer(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
    }

    @PostConstruct
    public void start() throws InterruptedException {

        // 配置NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 服务器辅助启动类配置
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加自定义协议的编解码工具
                            ch.pipeline().addLast(new SmartCarEncoder());
                            ch.pipeline().addLast(new SmartCarDecoder());
                            // 处理 业务请求
                            ch.pipeline().addLast(new SimpleHandler());

                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 1024) // 设置tcp缓冲区 // (5)
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            System.out.println("netty server start .....");

            // 绑定端口 同步等待绑定成功
            ChannelFuture f = b.bind(port).sync(); // (7)
            // 等到服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅释放线程资源
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }



    }


    public static void main(String[] args) throws InterruptedException {
        new RpcServer("127.0.0.1" , 8088).start();
    }

}
